package com.mdb.open.epay.service.epay.biz.service;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.mdb.bc.api.data.ResultEx;
import com.mdb.bc.utils.ObjectUtil;
import com.mdb.open.epay.common.MdbDataSource;
import com.mdb.open.epay.service.epay.EpQuotaLimitService;
import com.mdb.open.epay.service.epay.QpSignSerialService;
import com.mdb.open.epay.service.epay.QpSignService;
import com.mdb.open.epay.service.epay.QpUserOpenService;
import com.mdb.open.epay.service.epay.biz.bo.SignBizBo;
import com.mdb.open.epay.service.epay.biz.bo.UnsignBizBo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author liuyi
 * @date 2019/11/18
 **/
@Service
@DS(MdbDataSource.EPAY)
public class SignBizService {

    /**
     * 签约流水
     */
    @Autowired
    private QpSignSerialService qpSignSerialService;
    /**
     * 签约信息
     */
    @Autowired
    private QpSignService qpSignService;

    /**
     * 开通信息
     */
    @Autowired
    private QpUserOpenService qpUserOpenService;

    /**
     * 限額限次
     */
    @Autowired
    private EpQuotaLimitService epQuotaLimitService;


    @Transactional
    public ResultEx sign(SignBizBo bizBo) {
        //保存签约流水
        boolean qpSignSerialSave = qpSignSerialService.save(bizBo.getQpSignSerial());
        if (!qpSignSerialSave) {
            return ResultEx.fail();
        }
        //保存签约信息
        boolean qpSignSave = qpSignService.saveOrUpdate(bizBo.getQpSign());
        if (!qpSignSave) {
            return ResultEx.fail();
        }
        //保存开通信息
        if (ObjectUtil.isNotEmpty(bizBo.getQpUserOpen())) {
            boolean qpUserOpenCount = qpUserOpenService.save(bizBo.getQpUserOpen());
            if (!qpUserOpenCount) {
                return ResultEx.fail();
            }
        }
        //新增或修改限额配置信息
        //限額
        if (ObjectUtil.isNotEmpty(bizBo.getEpQuotaLimit())) {
            boolean epQuotaLimitSave = epQuotaLimitService.saveOrUpdate(bizBo.getEpQuotaLimit());
            if (!epQuotaLimitSave) {
                return ResultEx.fail();
            }
        }
        //限次
        if (ObjectUtil.isNotEmpty(bizBo.getEpTimesLimit())) {
            boolean epTimesLimitSave = epQuotaLimitService.saveOrUpdate(bizBo.getEpTimesLimit());
            if (!epTimesLimitSave) {
                return ResultEx.fail();
            }
        }

        return ResultEx.ok();
    }

    @Transactional
    public ResultEx unsign(UnsignBizBo bizBo) {
        //保存签约流水
        boolean qpSignSerialCount = qpSignSerialService.save(bizBo.getQpSignSerial());
        if (!qpSignSerialCount) {
            return ResultEx.fail();
        }
        //修改签约信息 狀態
        boolean qpSignCount = qpSignService.saveOrUpdate(bizBo.getQpSign());
        if (!qpSignCount) {
            return ResultEx.fail();
        }
        return ResultEx.ok();
    }
}
